<template>
	<div>
		<Tabs>
			<TabPane label="编辑满减满赠"></TabPane>
		</Tabs>
		
		<div class="ui-tab-navs">
			<a
				class="ui-tab-navs-cell"
				href="javascript:;"
				v-for="item in types"
				:class="{active: formData.type == item.type, disabled: formData.id && formData.type != item.type}"
				@click="handleChangeType(item.type)"
			>
				<p class="title">{{ item.title }} </p>
				<p class="desc">（{{ item.desc }}）</p>
			</a>
		</div>
		<p style="margin-top: 15px;">注意：一旦选择满减满赠类型并新增成功后，满减满赠类型不可变</p>
		<Divider />
		
		<Form ref="form" :model="formData" :rules="rules" label-position="top">
			<FormDescItem label="活动名称" prop="title" desc="给满减满赠活动定一个名称，多个活动名称不可重复，建议不超过20个字">
				<Input v-model="formData.title" />
			</FormDescItem>
			<FormDescItem label="有效期设置" desc="请选择满减满赠活动生效日期及到期日期">
				<DatePicker v-model="formData.time_terms" type="datetimerange" placeholder="请选择日期"></DatePicker>
			</FormDescItem>
			<Divider />
			
			<div v-if="formData.type == 1 || formData.type == 2">
				<FormDescItem label="活动方式" desc="设置满减满赠活动方式">
					<RadioGroup v-model="formData.active_type" @on-change="handleChangeActiveType">
		                <Radio :label="1">固定{{ formData.type == 1 ? '金额' : '件数' }}满减</Radio>
		                <Radio :label="2">阶梯满减</Radio>
		            </RadioGroup>
				</FormDescItem>
				<ui-box class="ui-form-card-box" v-for="(item, index) in formData.active_content" :key="index" :closeable="index != 0" @on-close="handleDeleteActive(index)">
					<FormDescItem
						:label="'满足'+ (formData.type == 1 ? '金额' : '件数') + (formData.active_type == 2 ? '('+ (index + 1) +'阶活动)' : '')"
						desc="设置活动参与的满足金额条件，必须为正整数，且金额大于0"
					>
						<InputNumber v-model="item.limit_amount" :min="1" :precision="0"></InputNumber>
					</FormDescItem>
					<FormDescItem label="立减金额" desc="设置活动参与达到满足金额条件时的优惠金额，必须为正整数，且金额大于0">
						<InputNumber v-model="item.amount" :min="1" :precision="0"></InputNumber>
					</FormDescItem>
				</ui-box>
				<Button v-if="formData.active_type == 2" icon="md-add" @click="handleAddActive" style="margin-bottom: 20px;">添加一组活动促销</Button>
			</div>
			<div v-else>
				<FormDescItem
					:label="'满足'+ (formData.type == 3 ? '金额' : '件数')"
					desc="设置活动参与的满足金额条件，必须为正整数，且金额大于0"
				>
					<InputNumber v-model="formData.gift_limit_amount" :min="1" :precision="0"></InputNumber>
				</FormDescItem>
				<FormItem label="赠送礼品">
					<Button type="primary" @click="handleShowGoodsModal('gift')">选择赠品</Button>
					<div class="ui-goods-cells">
						<div class="ui-goods-cells__item" v-for="(item, index) in selectedGifts">
							<div class="delete" @click="handleDeleteGift(index)"><Icon type="md-close-circle" :size="16" color="#ed4014" /></div>
							<ImageCell :src="item.thumb" :width="120"></ImageCell>
							<p class="ui-ellipsis2 title">{{ item.sku_name }}</p>
						</div>
					</div>
				</FormItem>
			</div>
			
			<FormDescItem label="循环累加" desc="设置允许后，活动满足金额可循环累加，如满100减10元，允许循环累加，则满200减20，反之则无论超过满足金额多少仅减一次">
				<RadioGroup v-model="formData.is_loop">
	                <Radio :label="1">允许</Radio>
	                <Radio :label="0">不允许</Radio>
	            </RadioGroup>
			</FormDescItem>
			<Divider />
			<FormDescItem label="开启状态" desc="设置活动的开启状态">
				<RadioGroup v-model="formData.status">
	                <Radio :label="1">开启</Radio>
	                <Radio :label="0">关闭</Radio>
	            </RadioGroup>
			</FormDescItem>
			<FormDescItem label="活动限制" desc="设置参与活动的使用限制，单一商品同一时段只能参与一种满减满赠活动">
				<RadioGroup v-model="formData.active_limit">
	                <Radio :label="1">全场商品可用</Radio>
	                <Radio :label="2">指定商品可用</Radio>
	            </RadioGroup>
			</FormDescItem>
		</Form>
		
		<template v-if="formData.active_limit == 2">
			<div>
				<Button type="primary" @click="handleShowGoodsModal('goods')">设置商品</Button>
			</div>
			<div v-if="selectedSkus.length > 0" style="margin-top: 15px;">
				<Table
			    	ref="table"
			    	:data="selectedSkus"
			    	:columns="columns"
			    >
			    	<div class="ui-table-cell ui-flex" slot-scope="{ row }" slot="goods">
			    		<ImageCell :src="row.thumb"></ImageCell>
			            <div class="ui-flex-full" style="margin-left: 10px;">
			            	<p class="ui-ellipsis2">{{ row.sku_name }}</p>
			            	<p class="ui-ellipsis ui-text-primary">{{ handleGetSpecTexts(row) }}</p>
			            </div>
			        </div>
			        <div slot-scope="{ row }" slot="price">
			        	<ui-price :value="row.shop_price"></ui-price>
			        </div>
			        <div slot-scope="{ row }" slot="action">
			        	<Button type="error" size="small" @click="handleDelete(row.sku_id)">删除</Button>
			        </div>
			    </Table>
			</div>
		</template>
		
		<SelectGoods ref="goodsModal" v-model="showGoodsModal" :selected-data="selectedGoods" @on-change="handleChangeGoods"></SelectGoods>
		
		<LoadingMask v-if="loading"></LoadingMask>
		
		<FooterBar>
			<div style="text-align: center;">
				<Button @click="handleBack">返回列表</Button>
				<Button type="primary" @click="handleSubmit" :loading="commiting">保存设置</Button>
			</div>
		</FooterBar>
	</div>
</template>

<script>
import Util from '@/libs/util.js';
import Tools from '@/libs/tools.js';
import FooterBar from '@/components/FooterBar.vue';
import FormDescItem from '@/components/form/FormDescItem.vue';
import SelectGoods from '@/components/SelectGoods.vue';
import ImageCell from '@/components/ImageCell/index.vue';
import LoadingMask from '@/components/LoadingMask.vue';
export default {
	name: 'couponEdit',
	components: {
		FooterBar,
		FormDescItem,
		SelectGoods,
		ImageCell,
		LoadingMask
	},
	data() {
		return {
			loading: false,
			commiting: false,
			showGoodsModal: false,
			types: [
				{
					type: 1,
					title: '满额立减',
					desc: '达到金额立减'
				},
				{
					type: 2,
					title: '满件立减',
					desc: '达到件数立减'
				},
				{
					type: 3,
					title: '满额送礼',
					desc: '达到金额赠礼'
				},
				{
					type: 4,
					title: '满件送礼',
					desc: '达到件数赠礼'
				}
			],
			selectedGoods: [],
			selectedGoodsType: '',
			selectedSkus: [],
			selectedGifts: [],
			formData: {
				id: null,
				type: 1,
				status: 1,
				title: '',
				time_terms: [],
				active_type: 1,
				active_limit: 1,
				is_loop: 1,
				active_content: [
					{ limit_amount: 1, amount: 1 }
				],
				gift_limit_amount: 1
			},
			rules: {
				title: [
					{required: true, message: '请输入优惠券名称', trigger: 'blur'}
				]
			},
			columns: [
                {
                    title: '商品',
                    slot: 'goods'
                },
                {
                    title: '价格',
                    slot: 'price',
                    width: 150
                },
                {
                    title: '库存',
                    key: 'number',
                    width: 150
                },
                {
                    title: '操作',
                    slot: 'action',
                    align: 'center',
                    width: 80
                }
			]
		}
	},
	mounted() {
		if(this.$route.query.id) {
    		this.formData.id = this.$route.query.id;
    		this.init();
    	}
	},
	methods: {
		init() {
			this.loading = true;
			Util.ajax.post(this.API['ADDONS_PROMOTION_GOODS_DETAIL'], {id: this.formData.id}).then(res => {
				this.loading = false;
				this.formData.type = res.type;
				this.formData.title = res.title;
				this.formData.status = res.status;
				this.formData.time_terms = [res.start_time * 1000, res.end_time * 1000];
				this.formData.active_limit = res.active_limit;
				this.formData.active_type = res.active_type;
				this.formData.is_loop = res.is_loop;
				
				if(res.type == 1 || res.type == 2) {
					if(res.active_type == 1) {
						this.formData.active_content[0] = res.active_content;
					}else{
						this.formData.active_content = res.active_content;
					}
				}else{
					this.formData.gift_limit_amount = res.active_content.limit_amount;
					this.selectedGifts = res.active_content.gifts;
				}
				
			}).catch(() => {
				
			})
		},
		// 选择优惠券类型
		handleChangeType(type) {
			if(this.formData.id) return false;
			this.formData.type = type;
		},
		// 改变活动方式
		handleChangeActiveType(value) {
			if(value == 1) {
				this.formData.active_content = this.formData.active_content.slice(0, 1);
			}
		},
		// 删除活动阶组
		handleDeleteActive(index) {
			this.formData.active_content.splice(index, 1);
		},
		// 添加活动阶组
		handleAddActive() {
			this.formData.active_content.push({ limit_amount: 1, amount: 1 });
		},
		// 删除赠品
		handleDeleteGift(index) {
			this.selectedGifts.splice(index, 1);
		},
		// 打开选择商品弹窗
		handleShowGoodsModal(type) {
			if(type == 'gift') {
				this.selectedGoods = this.selectedGifts.map(item => {
					return item;
				})
			}else{
				this.selectedGoods = this.selectedSkus.map(item => {
					return item;
				})
			}
			this.selectedGoodsType = type;
			this.showGoodsModal = true;
		},
		// 选择的商品
		handleChangeGoods(rows) {
			if(this.selectedGoodsType == 'gift') {
				this.selectedGifts = rows.map(item => {
					return item;
				});
			}else{
				this.selectedSkus = rows.map(item => {
					return item;
				});
			}
		},
		// 格式化规格数据
		handleGetSpecTexts(row) {
			if(Array.isArray(row.spec)) {
				let texts = row.spec.map(item => {
					return item.name +':'+ item.value;
				})
				return texts.join('、');
			}else{
				return row.spec.name +':'+ row.spec.value;
			}
		},
		// 删除选择的商品
		handleDelete() {
			this.selectedSkus = this.selectedSkus.filter(item => {
				return item.sku_id != id;
			})
		},
		// 返回上一级
		handleBack() {
			this.$router.back();
		},
		// 提交
		handleSubmit() {
            if(this.commiting) return false;
			this.$refs.form.validate((valid) => {
                if (valid) {
                	let form = this.formData;
                	
                	// 有效期
                	if(!form.time_terms[0]) {
                		this.$Message.error('请选择活动有效期');
						return false;
                	}
                	
                	// 验证是否选择赠品
                	if(form.type == 3 || form.type == 4) {
                		if(this.selectedGifts.length == 0) {
                			this.$Message.error('请至少选择一个赠品');
							return false;
                		}
                	}
                	
                	// 验证是否选择产品
                	if(form.active_limit == 2 && this.selectedSkus.length == 0) {
                		this.$Message.error('请至少选择一个参与活动的商品');
						return false;
                	}
                	
                    let params = {
                    	type: form.type,
                    	title: form.title,
                    	//start_time: Date.parse(new Date(form.time_terms[0])) / 1000,
                    	//end_time: Date.parse(new Date(form.time_terms[1])) / 1000,
                    	start_time: Tools.formatDate(form.time_terms[0], 'yyyy-MM-dd hh:mm:ss'),
                    	end_time: Tools.formatDate(form.time_terms[1], 'yyyy-MM-dd hh:mm:ss'),
                    	active_type: form.active_type,
                    	active_limit: form.active_limit,
                    	status: form.status,
                    	is_loop: form.is_loop
                    }
                    
                    // 立减时，type为1、2
                    if(form.type == 1 || form.type == 2) {
                    	if(form.active_type == 1) {
                    		params.active_content = form.active_content[0];
                    	}else{
                    		params.active_content = form.active_content;
                    	}
                    }else{
                    	// 赠礼，type为3、4
                    	params.active_content = {
                    		limit_amount: form.gift_limit_amount,
                    		gift_sku_ids: this.selectedGifts.map(item => {
                    			return item.sku_id;
                    		})
                    	}
                    }
                    
                    // 活动限制为指定商品可用时
                    if(form.active_limit == 2) {
                    	params.sku_ids = this.selectedSkus.map(item => {
                    		return item.sku_id;
                    	})
                    }
                    
                    this.commiting = true;
                    if(form.id) {
                    	params.id = form.id;
                    	Util.ajax.post(this.API['ADDONS_PROMOTION_GOODS_EDIT'], params).then((res) => {
	                    	this.commiting = false;
	                    	this.$Message.success({
	                    		content: '编辑成功',
	                    		onClose: () => {
	                    			this.handleBack();
	                    		}
	                    	})
	                    }).catch(() => {
	                    	this.commiting = false;
	                    })
                    }else{
                    	Util.ajax.post(this.API['ADDONS_PROMOTION_GOODS_CREATE'], params).then((res) => {
	                    	this.commiting = false;
	                    	this.$Message.success({
	                    		content: '添加成功',
	                    		onClose: () => {
	                    			this.handleBack();
	                    		}
	                    	})
	                    }).catch(() => {
	                    	this.commiting = false;
	                    })
                    }
                }
            })
		}
	}
}
</script>